package impl_v2.server;

import impl_v2.factory.FactoryImpl2;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;

import model.factory.Factory;
import model.server.AuctioningSystem2;

import org.jgroups.Channel;
import org.jgroups.JChannel;
import org.jgroups.blocks.RpcDispatcher;

public class AuctioningSystemServer2 {

	private static Registry registry;

	private static RpcDispatcher dispatcher;

	private static final String CLUSTER_NAME = "AuctioningSystemServiceGroup";
	private static final String SERVER_NAME = "rmi://localhost/AuctioningSystemService_";

	public static final String SERVER_REMOTE_EXCEPTION = "Error : Server disconnected !";

	public static void main(String args[]) {
		createServer();
	}

	public static void createServer() {
		try {
			try {
				registry = LocateRegistry.createRegistry(1099);
			} catch (RemoteException e) {
				registry = LocateRegistry.getRegistry(1099);
			}

			Factory factory = new FactoryImpl2();
			AuctioningSystem2 auctioningSystem = (AuctioningSystem2) factory.getAuctioningSystem();

			Channel channel = new JChannel(); // TODO parametres
			channel.connect(CLUSTER_NAME);
			channel.getState(null, 10000);
			dispatcher = new RpcDispatcher(channel, auctioningSystem);
			auctioningSystem.setDispatcher(dispatcher);

			System.out.println("Server id (String):");
			Scanner scanner = new Scanner(System.in);
			String serverId = scanner.nextLine();
			scanner.close();

			Naming.rebind(SERVER_NAME + serverId, auctioningSystem);
			auctioningSystem.addServerAddress(serverId);

			System.out.println("Server '" + serverId + "' started");
		} catch (RemoteException e) {
			System.err.println(AuctioningSystemServer2.SERVER_REMOTE_EXCEPTION);
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Server Error: " + e);
		}
	}

	public static void closeServer() {
		try {
			Naming.unbind("rmi://localhost/AuctioningSystemService");
			UnicastRemoteObject.unexportObject(registry, true);
			System.out.println("Server closed");
		} catch (RemoteException | MalformedURLException | NotBoundException e) {
			System.err.println(AuctioningSystemServer2.SERVER_REMOTE_EXCEPTION);
		}
	}
}
